#include "swmtaskstatus.h"

SWMTaskStatus::SWMTaskStatus()
{

}

/*
 *  取出指定Status的TaskID
 */
int SWMTaskStatus::getFirstTaskIDFromStatus(QString TaskStatus)
{
    QSqlQuery query;
    if(!query.exec(QString("select * from SWM_TaskStatus where TaskStatus='%1'").arg(TaskStatus)))
    {
        qWarning()<<query.lastError().text();
        return -1;
    }
    else {
        if(query.first())
        {
            int taskID = query.value("TaskID").toInt();
            return taskID;
        }
    }
    return -3;
}

/*
 *  创建任务
 */
int SWMTaskStatus::createTask()
{
    QSqlQuery query;
    if(!query.exec(QString("select * from SWM_TaskStatus where TaskStatus='正在执行'")))
    {
        qWarning()<<query.lastError().text();
        return -1;
    }
    else {
        if(query.first())
        {
            int taskID = query.value("TaskID").toInt();
            /*QMessageBox::StandardButton rb = QMessageBox::warning(NULL, "存在未执行完成的任务", "存在未执行完成的任务！\n是否继续执行任务?", QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
            if(rb == QMessageBox::Yes)
            {
                updateTaskStatus(taskID, "取消执行");
                return -2;
            }
            else
            {
                updateTaskStatus(taskID, "取消执行");
            }*/
            updateTaskStatus(taskID, "取消执行");
        }
    }

    if(!query.exec(QString("insert into SWM_TaskStatus(TaskStatus,StartTime) values('%1','now()')")\
                   .arg("正在执行")))
    {
        qWarning()<<query.lastError().text();
        return -1;
    }

    if(!query.exec(QString("select * from SWM_TaskStatus where TaskStatus='正在执行'")))
    {
        qWarning()<<query.lastError().text();
        return -1;
    }
    else {
        if(query.first())
        {
            int taskID = query.value("TaskID").toInt();
            return taskID;
        }
    }
    return -3;
}

/*
 *  更新任务状态
 */
bool SWMTaskStatus::updateTaskStatus(int taskID, QString status)
{
    QSqlQuery query;
    if(!query.exec(QString("UPDATE SWM_TaskStatus SET TaskStatus='%1' WHERE TaskID = '%2'")\
               .arg(status).arg(taskID)))
    {
        qWarning()<<query.lastError().text();
        return false;
    }
    return true;
}

/*
 *  删除任务
 */
bool SWMTaskStatus::deleteTask(int taskID)
{
    QSqlQuery query;
    if(!query.exec(QString("DELETE FROM SWM_TaskStatus WHERE TaskID = '%1'")\
               .arg(taskID)))
    {
        qWarning()<<query.lastError().text();
        return false;
    }
    return true;
}
